@include "lib.awk"
@include "globals.awk"

function new_Rows(_Rows) {
  a(w); a(gp); a(np); a(hi); a(lo); a(all); a(d)
}
function readcsv(com, _Rows,       rows,cols) {
  com = com ? com : "cat -"
  new_Rows(_Rows)
  while((com | getline)  > 0)  {
    gsub(/[ \t\r]/,"")
    gsub(/##.*/,"")
    if ($0) {
      rows ? row(rows,cols, _Rows) : header(cols,_Rows)
      rows++
    }
}}
function header(cols,_Rows,   n,i) { 
  for(i=1;i<=NF;i++)
    if ($i !~ /\~/) {
      n++
      cols[n]=i
      name[n]=$i
	    w[n]  = header_weight($i)
	    gp[n] = $i ~ /!/
	    np[n] = $i ~ /\$/
	    if (np[n])
        hi[n] = -1* (lo[n]=10^32)}
}
function header_weight(str,   w,n,tmp) {
  n=split(str,tmp,/\*/)
  return n==2 ? tmp[2]+0 : 1
}
function row(rows,cols,_Rows,   i,j,n) {
  all[rows]=rows
  if (NF  < length(cols))
    barph(FNR ": bad " NF " column, not " length(cols))
  else
    for(n in cols) {
      i = cols[n]
      d[rows][n]=$i
      if ($i != "?")
        if (np[n]) {
          if ($i > hi[n]) hi[n] = $i
          if ($i < lo[n]) lo[n] = $i }}
}
function dumpcsv(_Rows,    rows,row,cols,col,out) {
  rows=length(d)
  for(row=1;row<=rows;row++) {
    out = d[row][1]
    cols = length(d[row])
    for(col=2;col<=cols;col++)
      out = out "," d[row][col]
    print "["out"]" }
}

function _readcsv(      _Rows,o) {
  if (args("-d,data/weather.csv,--dump,0",o)) {
    readcsv("cat " o["-d"], _Rows)
    if (o["--dump"])
      dumpcsv(_Rows) }
}
